package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.LanProblemReq;
import com.cloud.lan.api.dto.resp.LanProblemResp;
import com.cloud.lan.api.dto.resp.LanUserResp;
import com.cloud.lan.config.cache.LoadingCacheConfiguration;
import com.cloud.lan.dao.LanProblemMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.model.dataobject.LanProblemDO;
import com.cloud.lan.service.ILanProblemService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 问卷调查 服务实现类
 * </p>
 *
 * @author xyqierkang@163.com
 * @since 2021-12-28
 */
@Slf4j
@Service
public class LanProblemServiceImpl extends ServiceImpl<LanProblemMapper, LanProblemDO> implements ILanProblemService {

    @Resource
    LoadingCacheConfiguration cacheConfiguration;
    @Resource
    private LanProblemMapper lanProblemMapper;

    @Override
    public BaseResponse<Object> getProblemUser(String token) {
        LanUserResp lanUserResp = cacheConfiguration.userInfo.getUnchecked(token);
        LambdaQueryWrapper<LanProblemDO> laQw = new LambdaQueryWrapper<>();
        laQw.eq(LanProblemDO::getUserId, lanUserResp.getUserId());
        LanProblemDO lanProblemDO = lanProblemMapper.selectOne(laQw);
        LanProblemResp resp = new LanProblemResp();
        BeanUtil.copyProperties(lanProblemDO, resp);
        return BaseResponse.success(resp);
    }

    @Override
    public BaseResponse<Object> add(LanProblemReq req) {
        log.info("#新增 问卷调查 {}", req);
        LanUserResp lanUserResp = cacheConfiguration.userInfo.getUnchecked(req.getToken());
        LambdaQueryWrapper<LanProblemDO> laQw = new LambdaQueryWrapper<>();
        laQw.eq(LanProblemDO::getUserId, lanUserResp.getUserId());
        LanProblemDO lanProblemDO = lanProblemMapper.selectOne(laQw);
        if (ObjectUtil.isNotEmpty(lanProblemDO)) {
            BeanUtil.copyProperties(req, lanProblemDO);
            lanProblemMapper.updateById(lanProblemDO);
            return BaseResponse.success();
//            log.error("add {} token {}", LanError.LAN_020006, req.getToken());
//            throw new BaseException(LanError.LAN_020006);
        }
        LanProblemDO ldo = new LanProblemDO();
        BeanUtil.copyProperties(req, ldo);
        ldo.setUserId(lanUserResp.getUserId());
        lanProblemMapper.insert(ldo);
        return BaseResponse.success();
    }
}
